package com.shapawan.tourism.controller;

import com.shapawan.tourism.entity.AdminUser;
import com.shapawan.tourism.service.AdminUserService;
import com.shapawan.tourism.util.JwtUtil;
import com.shapawan.tourism.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        log.info("用户尝试登录: {}", username);

        try {
            // 1. 根据用户名查询用户
            AdminUser user = adminUserService.getByUsername(username);

            // 2. 如果用户不存在，返回错误
            if (user == null) {
                log.warn("登录失败: 用户名不存在 - {}", username);
                return Result.error("用户名或密码错误");
            }
            
            // 3. 校验密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                log.warn("登录失败: 密码错误 - {}", username);
                return Result.error("用户名或密码错误");
            }

            // 4. 校验用户状态
            if (user.getStatus() != 1) {
                log.warn("登录失败: 用户已禁用 - {}", username);
                return Result.error("账号已被禁用");
            }
            
            // 5. 更新最后登录时间
            user.setLastLogin(new Date());
            adminUserService.updateById(user);

            String token = jwtUtil.generateToken(user);

            // 6. 清除敏感信息
            user.setPassword(null);

            // 7. 返回用户信息
            Map<String, Object> result = new HashMap<>();
            result.put("userInfo", user);
            result.put("token", token);

            log.debug("token: {}", token);

            log.info("用户登录成功: {}", username);
            return Result.success(result);
        } catch (Exception e) {
            log.error("登录异常: {} - {}", username, e.getMessage(), e);
            return Result.error("登录失败，系统异常");
        }
    }

    @GetMapping("/info")
    public Result<?> getUserInfo(@RequestParam(required = false) String username,
                                 @RequestHeader(value = "Username", required = false) String headerUsername) {
        // 优先使用参数中的用户名，其次使用请求头中的用户名
        String finalUsername = username != null ? username : headerUsername;

        if (finalUsername == null || finalUsername.trim().isEmpty()) {
            return Result.error("未提供用户名");
        }

        AdminUser user = adminUserService.getByUsername(finalUsername);
        if (user != null) {
            // 隐藏敏感信息
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    @PostMapping("/logout")
    public Result<?> logout() {
        return Result.success();
    }
} 